/* eslint-disable camelcase */

import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import { gql, useMutation } from '@apollo/client';

import notification from '@kuiper-components/notification';
import Dialog from '@kuiper-components/dialog';
import Button from '@kuiper-components/button';

import Textarea from '../../../../../components/Textarea';
import s from './Add.module.css';
import Label from '../../../../../components/Label';

const CREATE_GQL = gql`
	mutation($words: [String]!, $formSerializer: any) {
		explictKeywordWhitelistCreate(input: { words: $words })
			@rest(
				type: "ExplictKeywordWhitelistCreateResponse"
				path: "/kb/white_list_keywords"
				method: "POST"
				endpoint: "v2"
				bodySerializer: $formSerializer
			) {
			code
			msg
		}
	}
`;

export default function Add({ className, refetch, ...props }) {
	const [dialogVisible, setDialogVisible] = React.useState(false);
	const [text, setText] = React.useState('');
	const [warning, setWarning] = React.useState('');
	const [create] = useMutation(CREATE_GQL);

	const handleClose = () => {
		setText('');
		setWarning('');
		setDialogVisible(false);
		refetch && refetch();
	};
	const handleTextChange = e => {
		const text = e.target.value;
		setText(text);
		if (text.match(/\S{40}/)) {
			setWarning('单个词不允许超过40个字符');
		} else {
			setWarning('');
		}
	};
	const handleSubmit = () =>
		create({ variables: { words: text.trim().split(/\s+/) } })
			.then(() => {
				notification.success({
					message: `添加敏感词白名单成功`,
					placement: 'top',
				});
				handleClose();
			})
			.catch(error =>
				notification.error({
					message: `添加敏感词白名单失败`,
					description: error.message,
					placement: 'top',
				})
			);

	return (
		<>
			<Button
				primary
				className={cn(className, s.btn)}
				onClick={() => setDialogVisible(true)}
			>
				添加
			</Button>
			<Dialog
				visible={dialogVisible}
				destroyOnClose={true}
				title="白名单词设置"
				wrapClassName={s.dialog}
				{...props}
				onClose={handleClose}
				maskStyle={{ zIndex: 100 }}
			>
				<Label>敏感词</Label>
				<Textarea
					className={cn(s.textarea, { [s.hasWarning]: warning })}
					placeholder="请输入敏感词，按空格分隔，每个词敏感不超过40字符。"
					rows="10"
					value={text}
					onChange={handleTextChange}
				/>
				<div className={s.warning}>{warning}</div>
				<div className={s.actions}>
					<Button onClick={handleClose}>取消</Button>
					<Button primary onClick={handleSubmit}>
						添加
					</Button>
				</div>
			</Dialog>
		</>
	);
}

Add.propTypes = {
	className: PropTypes.string,
	refetch: PropTypes.func,
};

Add.defaultProps = {
	refetch: () => {},
};
